import {defaultOptions,renderAsync} from "docx-preview";
import renderImage from "./renders/image/index.js";
import renderPdf from "./renders/pdf/index.js";
import renderSheet from "./renders/xlsx/index.js";
import renderPptx from "./renders/pptx/index.js";
import renderMp4 from "./renders/mp4/index.js";
import renderText from "./renders/text/index.js";

// 假装构造一个vue的包装，让上层统一处理销毁和替换节点
const VueWrapper=(el)=>{
    return {
        $el:el,
        $destroy(){
            
        }
    };
};

const handler=[
    // 使用docxjs插件，目前效果最好的渲染器
    {
        accepts:["docx"],
        handler:async (buffer,target)=>{
            const docxOptions=Object.assign(defaultOptions,{
                debug:true,
                experimental:true
            });
            await renderAsync(buffer,target,null,docxOptions);
            return VueWrapper(target);
        }
    },
    // 图片过滤器
    {
        accepts:["gif","jpg","jpeg","bmp","tiff","tif","png","svg"],
        handler:async (buffer,target)=>{
            return renderImage(buffer,target);
        }
    },
    // 使用pdfjs渲染pdf，效果最好
    {
        accepts:["pdf"],
        handler:async (buffer,target)=>{
            return renderPdf(buffer,target);
        }
    },
    // 使用sheetjs + handsontable
    {
        accepts:["xlsx"],
        handler:async (buffer,target)=>{
            return renderSheet(buffer,target);
        }
    },
    // 使用pptx2html，已通过默认值更替
    {
        accepts:["pptx"],
        handler:async (buffer,target)=>{
            await renderPptx(buffer,target,null);
            window.dispatchEvent(new Event("resize"));
            return VueWrapper(target);
        }
    },
    {
        accepts:["mp4"],
        handler:async (buffer,target)=>{
            renderMp4(buffer,target);
            return VueWrapper(target);
        }
    },
    {
        accepts:["txt","json","js","css","java","py","html","jsx","ts","tsx","xml","md","log"],
        handler:async (buffer,target)=>{
            return renderText(buffer,target);
        }
    },
    // 错误处理
    {
        accepts: ["error"],
        handler: async (buffer, target, type) => {
            target.innerHTML = `
                <div style="text-align: center; margin-top: 80px">
                    不支持.${type}格式的在线预览，请下载后预览或转换为支持的格式
                </div>
                <div style="text-align: center">
                    支持docx, xlsx, pptx, pdf, 以及纯文本格式和各种图片格式的在线预览
                </div>
            `;
            return VueWrapper(target);
        }
    }
];

// 输出匹配
export default handler.reduce((prev,{accepts,handler})=>{
    accepts.forEach((item)=>{
        prev[item]=handler;
    });
    return prev;
},{});